import React, {Component} from 'react';
import {Link,withRouter} from "react-router-dom"
import {Menu, Icon} from "antd"
import logo from "../../assets/images/logo.png"
import "./index.less"
import menuList from "../../config/menuConfig";

const {SubMenu} = Menu;

class LeftNav extends Component {


    /**
     * 通过reduce+递归
     */
    getMenuNodes = (menuList) => {
        const path = this.props.location.pathname
        return menuList.reduce((pre, item) => {
            if (!item.children) {
                // 向pre添加Menu.Item
                 pre.push((
                    <Menu.Item key={item.key}>
                        <Link to={item.key}>
                            <Icon type={item.icon}/>
                            <span>{item.title}</span>
                        </Link>

                    </Menu.Item>
                ))
            } else {

                // 查找一个与当前请求路径匹配的子Item
                // path.indexOf(cItem.key) === 0 indexOf()返回0说明已经找到
                const cItem = item.children.find(cItem=>path.indexOf(cItem.key) === 0)

                // console.log('path',path)


                // 如果存在,说明当前Item的子列表要展开
                if(cItem){
                    this.openKey = item.key
                }

              pre.push((
                    <SubMenu
                        key={item.key}
                        title={
                            <span>
                                             <Icon type={item.icon}/>
                                             <span>{item.title}</span>
                                         </span>
                        }
                    >
                        {/*根据每一项的children来调用此函数*/}
                        {this.getMenuNodes(item.children)}
                    </SubMenu>
                ))
            }
            return pre
        }, [])

    }
    // 在第一次render执行一次,为第一次render准备数据
    componentWillMount() {
        this.menuNodes = this.getMenuNodes(menuList)
    }

    render() {
        // 得到请求当前的路由路径
        const path = this.props.location.pathname
        // console.log(path)
        const openKey = this.openKey

        return (
            <div className="left-nav">
                <Link to="/" className="left-nav-header">
                    <img src={logo} alt="logo"/>
                    <h1>React后台</h1>
                </Link>

                <Menu
                    selectedKeys={[path]}
                    defaultOpenKeys={[openKey]}
                    mode="inline"
                    theme="dark"

                >


                    {
                        this.menuNodes
                    }

                </Menu>


            </div>
        );
    }
}

// 把不是通过路由切换过来的组件中，将react-router 的 history、location、match 三个对象传入props对象上

export default withRouter(LeftNav);
